package utils

import (
	"crypto/md5"
	"errors"
	"fmt"
	"github.com/hashicorp/go-uuid"
	"io"
)

var (
	UUIDMAP         map[string]string
	ParseUUID       map[string]string
	CardMapNum2UUID map[string]string
	CardMapUUID2Num map[string]string
)

// limit:每次返回的数据个数；offset:每次从第几个数据开始取，注意的是，offset=0 是从第一个数据开始
func Page(Limit, Page int) (limit, offset int) {
	if Limit > 0 {
		limit = Limit
	} else {
		limit = 10
	}

	if Page > 0 {
		offset = (Page - 1) * limit
	} else {
		offset = -1
	}
	return limit, offset
}

func Md5(str string) string {
	w := md5.New()
	io.WriteString(w, str)
	md5str := fmt.Sprintf("%x", w.Sum(nil))
	return md5str
}

//
func GetUUID(num string) (string, error) {
	var count int = 0
	myUUID, ok := UUIDMAP[num]
	if ok {
		return myUUID, nil
	}
BEGIN:
	tmp, err := uuid.GenerateUUID()
	if err != nil {
		if count < 3 {
			count++
			goto BEGIN
		}
		return "", errors.New("uuid生成错误")
	}
	UUIDMAP[num] = myUUID
	ParseUUID[myUUID] = num
	return tmp, nil

}

func GetNum(UUID string) (string, error) {
	res, ok := ParseUUID[UUID]
	if !ok {
		return "", errors.New("不存在的uuid")
	}
	return res, nil
}

func CardNum2UUID(num string) (string, error) {
	var count int = 0
	myUUID, ok := CardMapNum2UUID[num]
	if ok {
		return myUUID, nil
	}
BEGIN:
	tmp, err := uuid.GenerateUUID()
	if err != nil {
		if count < 3 {
			count++
			goto BEGIN
		}
		return "", errors.New("uuid生成错误")
	}
	CardMapNum2UUID[num] = myUUID
	CardMapUUID2Num[myUUID] = num
	return tmp, nil
}
func CardUUID2Num(UUID string) (string, error) {
	res, ok := CardMapUUID2Num[UUID]
	if !ok {
		return "", errors.New("不存在的uuid")
	}
	return res, nil
}
